package hash;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.SortedSet;
import interfaces.IItem;
import interfaces.ITransaction;
import common.Match;
import java.util.Iterator;
import java.util.Collections;



public class Table {
    int support;
    public Map<IItem,TableItem> table = new HashMap<IItem,TableItem>();
    //protected Map<IItem,TableItem> table = new HashMap<IItem,TableItem>();    
    
    public Table(double support, int windowSize){
        this.support = (int)Math.ceil(support * windowSize);
    }
    
    public TransactionItems addTransaction(ITransaction trans){
        List<IItem> items = trans.getItems();
        Collections.sort(items);
        TransactionItems ti = new TransactionItems();
        
        TableItem root;
        
        for (int i=0; i<items.size(); ++i){
            root = table.get(items.get(i));
            if (null==root){
                root = new TableItem(items,i,ti);
                table.put(root.item, root);
            }
            else{
                root.addChain(items, i, ti);
            }
        }
        
        return ti;
    }
    
    public void removeEmpty(){
        List<IItem> toRemove = new LinkedList<IItem>();
        
        Iterator<TableItem> it = table.values().iterator();
        
        TableItem ti;
        while (it.hasNext()){
            ti = it.next();
            if (ti.occurences == 0){
                toRemove.add(ti.item);
            }
        }
        
        for (IItem item:toRemove){
            table.remove(item);
        }
       
    }
    
    public List<Match> getPatterns(ITransaction emptyTransactionImpl){
        List<Match> matches = new LinkedList<Match>();
        Iterator<TableItem> it = table.values().iterator();

        TableItem ti;

        while(it.hasNext()){
            ti = it.next();
            ti.getMatches(matches, support, emptyTransactionImpl.deepcopy());
        }
        
        return matches;
    }
}
